package com.happok.onlineclass.usermanagement.setting.utils;

import com.happok.onlineclass.usermanagement.common.exception.DisableException;
import com.happok.onlineclass.usermanagement.common.exception.MisdirectedRequestException;
import com.happok.onlineclass.usermanagement.setting.dto.EmailVerifyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Properties;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/10/9 14:35
 */
@Slf4j
public class EmailUtil {
    public static void connectToEmail(String server, String mailFrom, String mailPWD) {
        if (ObjectUtils.isEmpty(server) ||
                ObjectUtils.isEmpty(mailFrom) ||
                ObjectUtils.isEmpty(mailPWD)) {
            throw new DisableException("邮箱平台设置异常");
        }
        Properties props = getProperties(server);
        Session session = Session.getInstance(props);
        try {
            Transport ts = session.getTransport();
            ts.connect(mailFrom, mailPWD);
            boolean isConnected = ts.isConnected();
            ts.close();
            if (!isConnected) {
                throw new MisdirectedRequestException(1, "邮箱服务器连接异常");
            }
        } catch (Exception e) {
            log.error("邮箱服务器测试异常{}" + e);
            throw new MisdirectedRequestException(1, "邮箱服务器连接异常");
        }
    }

    public static void sendEmailVerifyCode(String server, String mailFrom, String mailPWD,
                                           String email, Integer verifyCode, EmailVerifyDTO emailVerify) throws Exception {
        Properties props = getProperties(server);
        Session session = Session.getInstance(props);
        MimeMessage message = new MimeMessage(session);
        // 设置发送人，mailFrom 是邮箱号，mailName是昵称（支持中文）
        message.setFrom(new InternetAddress(mailFrom, mailFrom));
        // 是指收件人
        message.setRecipients(Message.RecipientType.TO, email);
        // 设置主题的编码方式
        message.setSubject(MimeUtility.encodeWord(emailVerify.getTopic(), "gbk", "Q"));
        String content = emailVerify.getContent().replace("${code}", verifyCode.toString());
        if (!ObjectUtils.isEmpty(emailVerify.getSignature())) {
            content = "【" + emailVerify.getSignature() + "】" + content;
        }
        // 设置内容的编码方式
        message.setContent(content, "text/html;charset=utf-8");
        message.saveChanges();
        //发送邮件
        Transport ts = session.getTransport();
        ts.connect(mailFrom, mailPWD);
        ts.sendMessage(message, message.getAllRecipients());
    }

    public static void sendEmailResetPwd(String server, String mailFrom, String mailPWD,
                                         String email, String pwd, EmailVerifyDTO emailVerify) throws Exception {
        Properties props = getProperties(server);
        Session session = Session.getInstance(props);
        MimeMessage message = new MimeMessage(session);
        // 设置发送人，mailFrom 是邮箱号，mailName是昵称（支持中文）
        message.setFrom(new InternetAddress(mailFrom, mailFrom));
        // 是指收件人
        message.setRecipients(Message.RecipientType.TO, email);
        // 设置主题的编码方式
        message.setSubject(MimeUtility.encodeWord(emailVerify.getTopic(), "gbk", "Q"));
        String content = emailVerify.getContent().replace("${password}", pwd);
        if (!ObjectUtils.isEmpty(emailVerify.getSignature())) {
            content = "【" + emailVerify.getSignature() + "】" + content;
        }
        // 设置内容的编码方式
        message.setContent(content, "text/html;charset=utf-8");
        message.saveChanges();
        //发送邮件
        Transport ts = session.getTransport();
        ts.connect(mailFrom, mailPWD);
        ts.sendMessage(message, message.getAllRecipients());
    }

    public static void sendEmailAddUser(String server, String mailFrom, String mailPWD,
                                        String email, String account, String pwd, EmailVerifyDTO emailVerify) throws Exception {
        Properties props = getProperties(server);
        Session session = Session.getInstance(props);
        MimeMessage message = new MimeMessage(session);
        // 设置发送人，mailFrom 是邮箱号，mailName是昵称（支持中文）
        message.setFrom(new InternetAddress(mailFrom, mailFrom));
        // 是指收件人
        message.setRecipients(Message.RecipientType.TO, email);
        // 设置主题的编码方式
        message.setSubject(MimeUtility.encodeWord(emailVerify.getTopic(), "gbk", "Q"));
        String content = emailVerify.getContent().replace("${account}", account);
        content = content.replace("${password}", pwd);
        if (!ObjectUtils.isEmpty(emailVerify.getSignature())) {
            content = "【" + emailVerify.getSignature() + "】" + content;
        }
        // 设置内容的编码方式
        message.setContent(content, "text/html;charset=utf-8");
        message.saveChanges();
        //发送邮件
        Transport ts = session.getTransport();
        ts.connect(mailFrom, mailPWD);
        ts.sendMessage(message, message.getAllRecipients());
    }

    private static Properties getProperties(String server) {
        Properties props = new Properties();
        // 发送的服务器
        props.setProperty("mail.host", server);
        // 协议
        props.setProperty("mail.transport.protocol", "smtp");
        // 授权
        props.setProperty("mail.smtp.auth", "true");
        // 使用465端口
        props.setProperty("mail.smtp.port", "465");
        // 采用SSL协议传输
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        return props;
    }
}